package www.dianbaozu.com.ui.chat.chat

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.gyf.immersionbar.ImmersionBar
import com.netease.nim.uikit.api.NIMHelper
import com.netease.nim.uikit.api.NimUIKit
import com.netease.nim.uikit.business.recent.RecentContactsFragment
import com.netease.nimlib.sdk.msg.constant.SystemMessageType
import com.zhengsr.tablib.bean.TabConfig
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.FlowPreview
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentChatBinding
import www.dianbaozu.com.ui.chat.chat.adapter.ChatTabFlowAdapter
import www.dianbaozu.com.ui.chat.friend.FriendFragment
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.ChatTabEntity
import www.wen.com.common.lib.data.entities.UnreadEntity
import www.wen.com.common.lib.extension.*
import www.wen.com.common.lib.helper.loading.KeyHelper

/**
 * @author WEN
 * @Description:主页聊天
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class ChatFragment : BaseLoadingFragment<FragmentChatBinding>(), View.OnClickListener {

    private val mFragments = mutableListOf(
        RecentContactsFragment(),
        FriendFragment()
    )

    private val chatViewModel: ChatViewModel by viewModels()

    override val viewModel: BaseViewModel
        get() = chatViewModel

    private val tabFlowAdapter by lazy {
        ChatTabFlowAdapter(
            R.layout.item_msg,
            mutableListOf(
                ChatTabEntity("私信", 0),
                ChatTabEntity("好友", NIMHelper.addFriendUnreadCount)
            )
        )
    }

    override fun getLayoutId(): Int = R.layout.fragment_chat

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ImmersionBar.setTitleBar(this, dataBinding.placeholderView)
    }

    override fun lazyInitView() {
        dataBinding.listener = this
        dataBinding.viewPager2.configuration(
            pageLimit = mFragments.size,
            provideAdapter = ::provideAdapter,
            onPageSelectedBA = ::onPageSelected
        )

        val config = TabConfig.Builder()
            .setViewpager(dataBinding.viewPager2)
            .setTextId(R.id.item_text)
            .setSelectedColor(Color.WHITE)
            .setUnSelectColor(getColorAgency(R.color.color999999))
            .build()
        dataBinding.tabVpFlowLayout.setAdapter(config, tabFlowAdapter)
        initObserver()

//        getAllFriendOnlineStatus()
    }

    private fun initObserver() {
        observeObjectSticky(KeyHelper.UNREAD_KEY, this, UnreadEntity::class.java) {
            if (this.type == UnreadEntity.TYPE_ADD_FRIEND) {
                tabFlowAdapter.datas[1].unreadCount = this.unreadCount
                tabFlowAdapter.notifyDataChanged()
            } else {
                tabFlowAdapter.datas[0].unreadCount = this.unreadCount
                tabFlowAdapter.notifyDataChanged()
            }
        }
    }

    override fun onClick(v: View) {
        when (v.id) {

            R.id.ivSearch -> {
                nav(R.id.action_mainFragment_to_findFriendsMessagesFragment)
            }

            R.id.ivAdd -> {
                nav(R.id.action_mainFragment_to_addFriendFragment)
//                好友请求列表
//                nav(R.id.action_mainFragment_to_friendRequestFragment)
//                好友请求拒绝列表
//                nav(R.id.action_mainFragment_to_refuseListFragment)
            }

        }
    }

    /**
     * 返回ViewPage2适配器
     */
    private fun provideAdapter(): FragmentStateAdapter {

        return object : FragmentStateAdapter(this) {

            override fun getItemCount(): Int = mFragments.size

            override fun createFragment(position: Int): Fragment = mFragments[position]

        }
    }

    /**
     * 联动
     */
    private fun onPageSelected(page: Int) {

    }

    @FlowPreview
    fun getAllFriendOnlineStatus() {
        val allFriendAccount = NIMHelper.getAllFriendAccount()
        if (allFriendAccount.isEmpty()) {
            return
        }
        chatViewModel.getUsersOnlineStatus(
            accids = allFriendAccount.toTypedArray(),
            action = {
                it.data.forEach { userInfo ->
                    NIMHelper.allFriendsLoginStatus[userInfo.accId] = userInfo.onlineStatus
                }
                //通知更新
                NimUIKit.notifyOnlineStateChange(allFriendAccount.toSet())
            })
    }

}



